<template>
  <BasicTable
    :initial-params="initialParams"
    :form-rules="formRules"
    :query-api="fetchList"
    :create-api="createUser"
    :update-api="updateUser"
    :delete-api="deleteUser"
    :query-fields="queryFields"
    :table-fields="tableFields"
    :form-fields="formFields"
    :button-permissions="buttonPermissions"
  ></BasicTable>
  <el-drawer v-model="drawerVisible" title="分配角色">
    <el-tree
      ref="treeRef"
      v-loading="drawerLoading"
      :data="roleData"
      :props="roleProps"
      show-checkbox
      :default-expand-all="true"
      :check-on-click-node="true"
      node-key="id"
    />
    <template #footer>
      <el-button type="primary" @click="handleConfirmAssignRole"
        >确定</el-button
      >
      <el-button @click="handleCancelAssignRole">取消</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="tsx">
import { ElMessage } from "element-plus";
import TreeStore from "element-plus/es/components/tree/src/model/tree-store";
import { onMounted, ref } from "vue";
import { fetchList as fetchRoleList } from "../../api/role";
import { station } from "../../api/station";
import {
  assignRole,
  createUser,
  deleteUser,
  fetchList,
  getRolesByUser,
  updateUser,
} from "../../api/user";
import BasicTable from "../../components/BasicTable.jsx";

const initialParams = {
  keyword: "",
  limit: 99999,
};

const formRules = {
  username: [{ required: true, message: "请输入账号" }],
  password: [{ required: true, message: "请输入密码" }],
  companyId: [{ required: true, message: "请绑定车站" }],
};

const queryFields = [
  {
    prop: "keyword",
    title: "用户名",
  },
];

const tableFields = [
  {
    prop: "id",
    title: "编号",
  },
  {
    prop: "username",
    title: "用户名",
  },
  {
    prop: "nickName",
    title: "姓名",
  },
  {
    prop: "email",
    title: "邮箱",
  },
  {
    prop: "note",
    title: "备注",
  },
  {
    title: "操作",
    action: true,
    slot: (row) => (
      <el-button
        v-has={buttonPermissions.role}
        link
        type="success"
        onClick={() => handleAssignRole(row)}
      >
        分配角色
      </el-button>
    ),
  },
];

const formFields = [
  {
    prop: "username",
    title: "用户名",
  },
  {
    prop: "nickName",
    title: "姓名",
  },
  {
    prop: "companyId",
    title: "车站",
    slot: (form) => (
      <el-select
        class="w-full"
        v-model={form.value.companyId}
        placeholder="车站"
      >
        {stationList.value.map((item) => (
          <el-option label={item.name} value={item.id}></el-option>
        ))}
      </el-select>
    ),
  },
  {
    prop: "email",
    title: "邮箱",
  },
  {
    prop: "password",
    title: "密码",
    slot: (form) => (
      <el-input v-model={form.value.password} type="password"></el-input>
    ),
  },
  {
    prop: "note",
    title: "备注",
  },
];

const drawerVisible = ref(false);

const roleProps = {
  label: "name",
};

const drawerLoading = ref(false);
const roleData = ref([]);
const treeRef = ref<TreeStore>();
const userId = ref();

async function handleAssignRole(row) {
  userId.value = row.id;
  drawerVisible.value = true;
  drawerLoading.value = true;
  try {
    let res = await fetchRoleList({ limit: 999999 });
    roleData.value = res.data.list;
    res = await getRolesByUser(row.id);
    treeRef.value.setCheckedKeys(
      res.data.map((item) => item.id),
      true
    );
  } finally {
    drawerLoading.value = false;
  }
}

async function handleConfirmAssignRole() {
  drawerLoading.value = true;
  try {
    const data = {
      adminId: userId.value,
      roleIds: treeRef.value.getCheckedKeys().join(","),
    };
    if (!data.roleIds) {
      ElMessage({ type: "error", message: "请选择角色" });
      return;
    }
    await assignRole(data);
    ElMessage({ type: "success", message: "操作成功" });
    drawerVisible.value = false;
  } finally {
    drawerLoading.value = false;
  }
}

function handleCancelAssignRole() {
  drawerVisible.value = false;
}

const buttonPermissions = {
  create: "authority-user:create",
  edit: "authority-user:edit",
  delete: "authority-user:delete",
  role: "authority-user:role",
};

const stationList = ref([]);
async function getStationList() {
  const res = await station.queryAll({ limit: 99999 });
  stationList.value = res.data.list;
}

onMounted(() => {
  getStationList();
});
</script>
